package hotel.controller.user;

import javafx.fxml.FXML;

import javafx.scene.control.Button;
import hotel.common.Md5;
import hotel.common.MsgBox;
import hotel.dao.HotelDao;
import hotel.modal.User;
import javafx.event.ActionEvent;
import javafx.scene.control.PasswordField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;

public class ChangeUserPasswdController {
	@FXML
	private Button btnOk;
	@FXML
	private Button btnCancel;
	@FXML
	private PasswordField passField;
	@FXML
	private PasswordField newPassField;
	@FXML
	private PasswordField newPassField2;
	
	User user = null;
	
	@FXML
    public void initialize() {
		passField.setOnKeyReleased(event -> {
			if (event.getCode() == KeyCode.ENTER) {
				changePasswd();
			}
		});
	}
	
	public void setInitData(User user) {
		this.user = user;
		if(user != null) user.setModified(false);
	}
	
	private void changePasswd() {
		Boolean check = true; 
		String pass = passField.getText();
		if(!Md5.getMD5(pass).equals(user.getPassword())) {
			check = false;
			MsgBox.showErrorDialog("密码修改错误", null, "原密码不正确！");
			passField.selectAll();
			passField.requestFocus();
		}
		
		if(check && !newPassField.getText().equals(newPassField2.getText())) {
			check = false;
			MsgBox.showErrorDialog("密码修改错误", null, "新密码不一致！请检查并重新输入新密码！");
			newPassField.clear();
			newPassField2.clear();
			newPassField.requestFocus();
		}
		
		if(check && newPassField.getText().equals(passField.getText())) {
			check = false;
			MsgBox.showErrorDialog("密码修改错误", null, "原密码与新密码不能一致！请重新输入！");
			newPassField.selectAll();
			newPassField2.clear();
			newPassField.requestFocus();
		}
		
		if(check) { // 如果检查没有问题执行密码修改操作
			Stage stage = (Stage)btnOk.getScene().getWindow();
			String prePass = user.getPassword();
			user.setPassword(Md5.getMD5(newPassField.getText())); // 将对象的密码设置成新的密码
			if(!HotelDao.changePassword(user)) {	// 写入数据库
				stage.hide();
				user.setPassword(prePass); // 如果密码没有成功修改，内部对象也设置回原来密码
				MsgBox.showErrorDialog("数据库错误", null, "密码修改没有成功!");
			}else {
				stage.hide(); // 隐藏窗口
				MsgBox.showInformationDialog("密码修改成功", null, 
						"当前用户("+user.getUserName()+")已成功修改密码！");
			}
			closeWindow();
		}
		
		check=true;
	}
	
	private void closeWindow() {
		Stage stage = (Stage)btnOk.getScene().getWindow();
		stage.close();
	}

	// Event Listener on Button[#btnOk].onAction
	@FXML
	public void onBtnOkAction(ActionEvent event) {
		changePasswd();
	}
	// Event Listener on Button[#btnCancel].onAction
	@FXML
	public void onBtnCancelAction(ActionEvent event) {
		closeWindow();
	}
}
